package cn.dyw.engine.core.template;

import cn.dyw.engine.core.context.DynamicFilterParameter;
import cn.dyw.engine.core.context.ReportStandardContext;
import cn.dyw.engine.core.exception.EngineRenderException;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.PropertyPlaceholderHelper;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * 默认实现的SQL模板引擎
 *
 * @author dyw770
 * @since 2021-08-03
 */
@Slf4j
public class DefaultTemplateEngine implements ITemplateEngine {


    @Getter
    @Setter
    private DynamicFilterPlaceholderResolver placeholderResolver;

    /**
     * 占位符处理
     */
    private final PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper(
            "${", "}", ":", false);

    public DefaultTemplateEngine() {
        this.placeholderResolver = new DynamicFilterPlaceholderResolver();
    }

    public DefaultTemplateEngine(DynamicFilterPlaceholderResolver placeholderResolver) {
        this.placeholderResolver = placeholderResolver;
    }

    @Override
    public String process(ReportStandardContext context) throws EngineRenderException {
        Map<String, DynamicFilterParameter> parameters = context.getParameters().stream()
                .collect(Collectors.toMap(DynamicFilterParameter::getParameterName,
                        item -> item));
        log.debug("渲染SQL: {}", context.getSqlTemplate());
        try {
            return helper.replacePlaceholders(context.getSqlTemplate(),
                    placeholderName -> placeholderResolver.resolvePlaceholder(placeholderName, parameters));
        } catch (Exception e) {
            log.debug("渲染SQL出错", e);
            throw new EngineRenderException("渲染SQL出错", e);
        }
    }
}
